package instancecreate

import (
	"bytes"
	"fmt"
	"github.com/bramvdbogaerde/go-scp"
	"gitee.com/laofa1/play/k_conf_mng/kconf_backend/pkg/setting"
	"gitee.com/laofa1/play/k_conf_mng/kconf_backend/pkg/util"
	"io/ioutil"
	"log"
	"text/template"
)

type NginxTemplateParam struct {
	MainDomain string
	CustomerSubDomain string
	AdminSubDomain string
	MobileSubDomain string
	CustomerPort int
	AdminPort int
	MobilePort int
	IP string
}

func GenerateNginx(param NginxTemplateParam) error {
	// read nginx template file and parse then scp to remote machine
	// apply nginx cert on remote machine
	nginxTemplate, err := ioutil.ReadFile(setting.NginxTemplate)
	if err != nil {
		return err
	}

	tmpl, err := template.New("nginx").Parse(string(nginxTemplate))
	if err != nil {
		return err
	}

	var nginxContent bytes.Buffer

	err = tmpl.Execute(&nginxContent, param)
	if err != nil {
		return err
	}

	sshConn, err := util.NewSshClient(
		setting.NginxHost, setting.NginxPort, setting.NginxName,
		setting.SshPrivateFile)
	if err != nil {
		return nil
	}
	defer func() {
		if err := sshConn.Close(); err != nil {
			log.Println(err)
		}
	}()

	// scp nginx config file
	scpClient, err := scp.NewClientBySSH(sshConn)
	if err != nil {
		log.Println(err)
		return err
	}
	defer scpClient.Close()

	err = scpClient.CopyFile(&nginxContent, "/tmp/" + param.CustomerSubDomain + ".conf", "0644")
	if err != nil {
		log.Println(err)
		return err
	}

	// run cerbot on remote machine
	output, err := util.RunSshCommand(
		sshConn,
		fmt.Sprintf(
			"sudo cp /tmp/%s.conf /etc/nginx/conf.d/;sudo certbot --nginx -d %s.%s -d %s.%s -d %s.%s --non-interactive --agree-tos",
			param.CustomerSubDomain,
			param.CustomerSubDomain, param.MainDomain,
			param.AdminSubDomain, param.MainDomain,
			param.MobileSubDomain, param.MainDomain,
		))
	if err != nil {
		log.Println(output)
		return err
	}
	return nil
}